package m.base.action;

import m.base.model.GoodsInfo;
import m.base.service.GoodsInfoService;
import m.base.util.PowerUtil;
import m.base.util.ZolUtil;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VuePageResult;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.Element;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.form.*;
import m.html.list.EventType;
import m.html.list.ListButton;
import m.html.list.ListEvent;
import m.html.list.SuccessMethod;
import m.store.service.StoreGoodsService;
import m.system.db.TransactionManager;
import m.system.util.ArrayUtil;
import m.system.util.JSONMessage;
import m.system.util.SystemUtil;
import manage.model.StatusModel;

@ActionMeta(name = "base/goodsInfo")
public class GoodsInfoAction extends BaseStatusAction{
    private GoodsInfo model;
    public VueResult toView() throws Exception {
        model=ModelQueryList.getModel(model,"*");
        return new VuePageResult("page/base/viewGoodsInfo.js")
                .addParam("model",model);
    }
    @RequestMeta(params = {"goodsUrl"})
    public JSONMessage doSave(String goodsUrl) throws Exception {
        PowerUtil.verifyPower(getStatusPower());
        String[] goodsUrls=goodsUrl.split("\n");
        int num=0;
        for(String gu : goodsUrls) {
            TransactionManager tm=new TransactionManager();
            try {
                tm.begin();
                model = getService(GoodsInfoService.class).doSave(ZolUtil.getOutId(gu));
                if(!StatusModel.Status_Enable.equals(model.getStatus())) {//不是启用状态再次采集
                    model = getService(GoodsInfoService.class).doCollection(model.getOid());
                }
                tm.commit();
                num++;
            }catch (Exception e){
                tm.rollback();
                SystemUtil.println("采集商品错误：",e.getMessage());
            }
        }
        return new JSONMessage(0,"成功采集了"+num+"条!");
    }
    @RequestMeta(params = {"goodsOid"},transaction = true)
    public JSONMessage doCollection(String goodsOid) throws Exception {
        PowerUtil.verifyPower(getStatusPower());
        model=getService(GoodsInfoService.class).doCollection(goodsOid);
        getService(StoreGoodsService.class).syncAttrJson(model);
        return new JSONMessage(0,"采集成功!");
    }
    public VueResult toCollection(){
        ModelForm form = new ModelForm("商品采集",1);
        form.addItem(
            FormInput.textarea("商品参数页面","goodsUrl").setPlaceholder("请输入商品url地址")
        )
        .addData("goodsUrl","")
        .addButton(
            FormButton.gho("转换url","convertGoodsUrl"),
            FormButton.pri("保存并采集","doSave")
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.toModal("convertGoodsUrl",actionUrl("convertGoodsUrl"),"{}",800)
                .fillData("goodsUrl"),
            FormEvent.doJson("doSave",actionUrl("doSave"),"{goodsUrl:this.goodsUrl}")
                .success("backFlag")
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form)
            .addForm(new CustomForm("提醒",false)
                .addElement(
                    Element.tag("a-alert").A("message","提醒").A("show-icon")
                    .E(
                        Element.tag("template").A("#description")
                        .E(
                            Element.tag("div").E("批量采集：每一行输入一个商品url")
                        )
                    )
                )
            );
    }
    @RequestMeta(params = {"text"})
    public JSONMessage getGoodsUrl(String text) throws Exception {
        return new JSONMessage(0, "").push("urls",ArrayUtil.connection(ZolUtil.getGoodsUrls(text),"\n"));
    }
    public VueResult convertGoodsUrl(){
        ModelForm form = new ModelForm("商品转换",1);
        form.addItem(
            FormInput.textarea("转换文本","text").setPlaceholder("请输入列表url地址或者页面源码")
        )
        .addData("text","")
        .addData("urls","")
        .addButton(
            FormButton.pri("确定","getGoodsUrl")
        )
        .addMethod(
            FormEvent.custom("backUrls","this.back(true,{goodsUrl:this.urls});"),
            FormEvent.doJson("getGoodsUrl",actionUrl("getGoodsUrl"),"{text:this.text}")
                    .fillData("urls").success("backUrls")
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form)
        .addForm(new CustomForm("提醒",false)
            .addElement(
                Element.tag("a-alert").A("message","提醒").A("show-icon")
                .E(
                    Element.tag("template").A("#description")
                    .E(
                        Element.tag("div").E("输入列表url地址或者页面源码转换成多个商品url地址。")
                    )
                )
            )
        );
    }
    /*
     * 商品信息列表
     */
    public VueResult allList() throws Exception {
        boolean power=PowerUtil.hasPower(getStatusPower());
        VueListResult result=getVueListResult("商品列表",GoodsInfo.class,actionUrl("allList"));
        result.setSubTitle("商品信息列表");
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.addCol(toTextColumn("类型", "typeName", 100, true));
        result.addCol(toTextColumn("厂商","factoryName",100,true));
        result.addCol(toLinkColumn("名称", "name", 300, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,700)
                .addParam("model.oid","oid")
        ));
//        result.addCol(toTextColumn("属性", "attrJson", 300, true));
        result.addCol(toStatusColumn(power,true));
        if(power) {
            result.addCol(toSpaceColumn("操作",
                ListButton.ajax("重新采集", ButtonType.DEFAULT, actionUrl("doCollection"), SuccessMethod.REFRESH)
                    .addParam("goodsOid", "oid").setConfirm("确定要重新采集吗？")
            ).setFixed(Align.RIGHT));
            result.setSelection("oid",false);
            result.addButton(
                ListButton.ajax("重新采集", ButtonType.DEFAULT, actionUrl("doCollection"), SuccessMethod.REFRESH)
                    .addParam("goodsOid", "oid").setConfirm("确定要重新采集吗？"),
                ListButton.modal("采集商品", ButtonType.PRIMARY, actionUrl("toCollection"), 700, SuccessMethod.REFRESH)
            );
        }
        //排序 result.addOrder
        //查询条件 result.addCondition
        return result;
    }
    @Override
    public String[] getStatusPower() {
        return new String[]{PowerUtil.SysData};
    }

    @Override
    public GoodsInfo getModel() {
        return model;
    }

    public void setModel(GoodsInfo model) {
        this.model = model;
    }
}
